<script setup>
import { ref,onMounted } from "vue"
import { onReachBottom,onPullDownRefresh } from "@dcloudio/uni-app"
   
 let goodsList = ref([])
 let total = ref(0)
 const queryObj = ref({query : '',cid : '',pagenum : 1,pagesize : 10})
 let isLoading = true
 
 async function getGoodsList(callback){
      const { data:res} = await uni.$http.get('/api/public/v1/goods/search', queryObj.value)
      callback && callback()
      if (res.meta.status !== 200){
        isLoading = true
        return uni.$showMsg()
      }
      goodsList.value = [...goodsList.value,...res.message.goods]
      total.value = res.message.total
      isLoading = false
 }
 
 onReachBottom(()=>{
    if(isLoading) return
    if(queryObj.value.pagenum * queryObj.value.pagesize >= total.value) return uni.$showMsg("没有更多了...")

    isLoading = true
    queryObj.value.pagenum += 1;
    getGoodsList()
 })
 
 onPullDownRefresh(()=>{
     // 1. 重置关键数据
     queryObj.value.pagenum = 1
     total.value = 0
     isLoading = true
     goodsList.value = []
     // 2. 重新发起请求
     getGoodsList(() => uni.stopPullDownRefresh())
 })
 
 //击跳转到商品详情页面
 function gotoDetail(goods_id) {
   uni.navigateTo({
     url: `/subpkg/goods_detail/goods_detail?goods_id=${goods_id}`
   })
 }
 
 onMounted(()=>{
     //获取get参数
     let curPage = (getCurrentPages().length)-1;
     queryObj.cid     = getCurrentPages()[curPage]['options']['cid'] || ''
     queryObj.query   = getCurrentPages()[curPage]['options']['query'] || ''
     getGoodsList()
 })
</script>

<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods.goods_id)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<style lang="scss">

</style>
